package com.shijun.im.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.shijun.im.activity.interactor.LoginInteractor;
import com.shijun.im.application.MyAppLication;
import com.shijun.im.config.HttpUrlAPI;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.ConnectionListener;
import org.jivesoftware.smack.SASLAuthentication;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.tcp.XMPPTCPConnection;
import org.jivesoftware.smack.tcp.XMPPTCPConnectionConfiguration;
import org.jivesoftware.smackx.iqregister.AccountManager;
import org.jxmpp.jid.parts.Localpart;
import org.jxmpp.stringprep.XmppStringprepException;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import static android.R.attr.port;

/**
 * Created by zhushijun on 2017/10/17 0017.
 */

public class IMService extends Service implements ConnectionListener {
    private static final String TAG = "IMService";
    private XMPPTCPConnection connection;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("TAG", "IMService onCreate");
        new Thread(new Runnable() {
            @Override
            public void run() {
                getConnection();
//                  connect();
            }
        }).start();

        ((MyAppLication) getApplication()).setIMService(this);
    }

    /**
     * 获得与服务器的连接
     *
     * @return
     */
    public XMPPTCPConnection getConnection() {
        try {
            if (connection == null) {
                XMPPTCPConnectionConfiguration config = XMPPTCPConnectionConfiguration.builder()
                        //服务器IP地址
                        .setHostAddress(InetAddress.getByName(HttpUrlAPI.IP))
                        .setHost(HttpUrlAPI.IP)
                        //服务器端口
                        .setPort(5222)
                        //服务器名称(管理界面的 主机名)
                        .setXmppDomain(HttpUrlAPI.IP)
                        //是否开启安全模式
                        .setSecurityMode(XMPPTCPConnectionConfiguration.SecurityMode.disabled)
                        //是否开启压缩
                        .setCompressionEnabled(false)
                        //开启调试模式
                        .setDebuggerEnabled(true).build();
                connection = new XMPPTCPConnection(config);
                connection.addConnectionListener(this);
                connection.connect();
            }
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 登录
     *
     * @param userName 用户名
     * @param password 密码
     */
    public boolean login(String userName,String password) {
        try {
            connection.setReplyTimeout(20*1000);
            SASLAuthentication.blacklistSASLMechanism("SCRAM-SHA-1");
            connection.login(userName, password);
        } catch (XMPPException e) {
            e.printStackTrace();
            return false;
        } catch (SmackException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 退出登录
     *
     * @return code
     * @code true 退出成功
     * @code false 退出失败
     */
    public boolean logout() {
        try {
            connection.instantShutdown();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    /**
     * 修改密码
     *
     * @param newPassword 　新密码
     * @return code
     * @code true 修改成功
     * @code false 修改失败
     */
    public boolean changePassword(String newPassword) {
        try {
            AccountManager manager = AccountManager.getInstance(connection);
            manager.changePassword(newPassword);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }


    @Override
    public IBinder onBind(Intent intent) {

        return new IMServiceBinder();
    }

    @Override
    public void connected(XMPPConnection xmppConnection) {
        Log.i("TAG", "连接上了");
    }

    @Override
    public void authenticated(XMPPConnection xmppConnection, boolean b) {
        Log.i("TAG", "authenticated");
    }

    @Override
    public void connectionClosed() {
        Log.i("TAG", "connectionClosed");
    }

    @Override
    public void connectionClosedOnError(Exception e) {
        Log.i("TAG", "connectionClosedOnError");
    }

    @Override
    public void reconnectionSuccessful() {
        Log.i("TAG", "重连");
    }

    @Override
    public void reconnectingIn(int i) {

    }

    @Override
    public void reconnectionFailed(Exception e) {

    }

    public class IMServiceBinder extends Binder {
        /**
         * 获取当前Service的实例
         *
         * @return
         */
        public IMService getService() {
            return IMService.this;
        }
    }
}
